import request from '@/utils/request'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import { 
  getAreaJurisdictionList,
  deleteAreaJurisdiction,
  batchDeleteAreaJurisdiction,
  toggleAreaJurisdictionStatus,
  getProvinceList,
  getCityList
} from '@/api/campus/areaJurisdiction'
import CustomForm from './Form/index.vue'

export default {
  name: 'areaJurisdiction',
  components: { CustomForm },
  data() {
    return {
      query: {
        areaCode: undefined,
        provinceId: undefined,
        cityId: undefined,
        enabledMark: undefined
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      },
      formVisible: false,
      areaOptions: [],
      provinceOptions: [],
      cityOptions: []
    }
  },
  computed: {},
  mounted() {
    // 获取管理区域选项
    getDictionaryDataSelector('MANAGEMENT_AREA').then(res => {
      this.areaOptions = res.data.list
    })
    
    // 获取省份选项
    this.getProvinceOptions()
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      getAreaJurisdictionList(query).then(res => {
        this.list = res.data.list || []
        this.total = res.data.pagination ? res.data.pagination.total : 0
        this.listLoading = false
      }).catch(error => {
        this.listLoading = false
        this.$message({
          type: 'error',
          message: error.msg || '获取数据失败，请重试'
        })
        this.list = []
        this.total = 0
      })
    },
    getProvinceOptions() {
      getProvinceList().then(res => {
        this.provinceOptions = res.data || []
      }).catch(() => {
        // 如果没有省份接口，使用模拟数据
        this.provinceOptions = [
          { id: '110000', fullName: '北京市' },
          { id: '120000', fullName: '天津市' },
          { id: '130000', fullName: '河北省' },
          { id: '140000', fullName: '山西省' },
          { id: '320000', fullName: '江苏省' },
          { id: '370000', fullName: '山东省' },
          { id: '610000', fullName: '陕西省' }
        ]
      })
    },
    handleProvinceChange(provinceId) {
      this.query.cityId = undefined
      this.cityOptions = []
      if (provinceId) {
        getCityList(provinceId).then(res => {
          this.cityOptions = res.data || []
        }).catch(() => {
          // 如果没有城市接口，使用模拟数据
          if (provinceId === '320000') {
            this.cityOptions = [
              { id: '320100', fullName: '南京市' },
              { id: '320300', fullName: '徐州市' },
              { id: '320500', fullName: '苏州市' }
            ]
          } else if (provinceId === '140000') {
            this.cityOptions = [
              { id: '140100', fullName: '太原市' },
              { id: '140200', fullName: '大同市' }
            ]
          }
        })
      }
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          deleteAreaJurisdiction(id).then(res => {
            this.$message({
              type: 'success',
              message: res.msg || '删除成功',
              onClose: () => {
                this.initData()
              }
            })
          }).catch(error => {
            this.$message({
              type: 'error',
              message: error.msg || '删除失败，请重试'
            })
          })
        })
        .catch(() => {})
    },
    handleSelectionChange(val) {
      const res = val.map(item => item.id)
      this.multipleSelection = res
    },
    handleBatchRemoveDel() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请选择一条数据',
          duration: 1500
        })
        return
      }
      const ids = this.multipleSelection
      this.$confirm('您确定要删除这些数据吗, 是否继续？', '提示', {
        type: 'warning'
      })
        .then(() => {
          batchDeleteAreaJurisdiction(ids).then(res => {
            this.$message({
              type: 'success',
              message: res.msg || '批量删除成功',
              onClose: () => {
                this.initData()
              }
            })
          }).catch(error => {
            this.$message({
              type: 'error',
              message: error.msg || '批量删除失败，请重试'
            })
          })
        })
        .catch(() => {})
    },
    handleToggleStatus(row) {
      const newStatus = row.enabledMark == 1 ? 0 : 1
      const statusText = newStatus == 1 ? '启用' : '禁用'
      
      this.$confirm(`确定要${statusText}该配置吗？`, '提示', {
        type: 'warning'
      })
        .then(() => {
          toggleAreaJurisdictionStatus(row.id, { enabledMark: newStatus }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg || `${statusText}成功`,
              onClose: () => {
                this.initData()
              }
            })
          }).catch(error => {
            this.$message({
              type: 'error',
              message: error.msg || `${statusText}失败，请重试`
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      }
      this.initData()
    },
    reset() {
      this.query = {
        areaCode: undefined,
        provinceId: undefined,
        cityId: undefined,
        enabledMark: undefined
      }
      this.cityOptions = []
      this.search()
    }
  }
}